package docker_util

import (
	"context"
	"fmt"
	"github.com/distribution/reference"
	"github.com/docker/docker/api/types/image"
	"github.com/docker/docker/api/types/registry"
	"github.com/docker/docker/client"
	"os"
)

func main() {
	// 创建 Docker 客户端
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
		fmt.Println("Error creating Docker client:", err)
		return
	}

	// 定义Harbor地址和认证信息
	harborAddress := "your-harbor-address.com"
	username := "your-username"
	password := "your-password"

	// 登录到Harbor
	authConfig := registry.AuthConfig{
		Username:      username,
		Password:      password,
		ServerAddress: harborAddress,
	}
	authResp, err := cli.RegistryLogin(context.Background(), authConfig)
	if err != nil {
		fmt.Println("Error logging in to Harbor:", err)
		return
	}
	fmt.Println("Login successful:", authResp.Status)

	// 定义镜像名称和目标镜像标签
	localImage := "your-local-image:tag"
	harborImage := fmt.Sprintf("%s/%s", harborAddress, "your-repo/your-image:tag")

	// 标记镜像
	parsedRef, err := reference.ParseNormalizedNamed(harborImage)
	if err != nil {
		fmt.Println("Error parsing image name:", err)
		return
	}

	if err := cli.ImageTag(context.Background(), localImage, harborImage); err != nil {
		fmt.Println("Error tagging image:", err)
		return
	}
	fmt.Println("Image tagged successfully:", harborImage)

	// 推送镜像到Harbor
	pushOptions := image.PushOptions{
		RegistryAuth: authResp.IdentityToken,
	}

	// 通过 Docker API 推送镜像
	pushResponse, err := cli.ImagePush(context.Background(), parsedRef.String(), pushOptions)
	if err != nil {
		fmt.Println("Error pushing image:", err)
		return
	}
	defer pushResponse.Close()

	// 打印推送过程中的输出（类似于 Docker CLI 的输出）
	_, err = os.Stdout.ReadFrom(pushResponse)
	if err != nil {
		fmt.Println("Error reading push response:", err)
		return
	}

	fmt.Println("Image pushed to Harbor successfully.")
}
